package com.andy.network.base

import com.andy.network.BuildConfig
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @creator:LuoFan
 * @date:2022/9/28
 * @description:
 */
abstract class BaseRetrofitClient {

    private val timeOut = 10L

    private val okHttpClient: OkHttpClient by lazy {
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(genLogInterceptor())
        builder.callTimeout(timeOut, TimeUnit.SECONDS)
        handleBuilder(builder)
        builder.build()
    }

    private fun genLogInterceptor(): Interceptor {
        val logInterceptor = HttpLoggingInterceptor()
        if (BuildConfig.DEBUG) {
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logInterceptor.level = HttpLoggingInterceptor.Level.NONE
        }
        return logInterceptor
    }

    abstract fun handleBuilder(builder: OkHttpClient.Builder)

    open fun <T> getService(service: Class<T>, baseUrl: String): T {
        return Retrofit.Builder().baseUrl(baseUrl).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build().create(service)
    }
}